//
//  CacheManager.swift
//  BasicTools
//
//  Created by ikang on 2025/8/28.
//

import Foundation
import SwiftUI

public struct CacheManager {
    
    // 计算缓存文件大小
    static public func fileSizeOfCache() -> String {
        // 取出cache文件夹目录，缓存文件都在这个目录下
        guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else { return "0.00 M" }
        
        // 取出文件夹下所有文件数组
//        let fileArr = try? FileManager.default.contentsOfDirectory(atPath: cachePath)
        let fileArr = FileManager.default.subpaths(atPath: cachePath)
        
        var size: Float = 0
        fileArr?.forEach { file in
            // 把文件名拼接到路径中
            let path = cachePath.appending("/\(file)")
            // 取出文件属性
            if let floder = try? FileManager.default.attributesOfItem(atPath: path) {
                // 用元祖取出文件大小属性
                if let fileSize = floder[FileAttributeKey.size] as? Float {
                    size += fileSize
                }
            }
        }
        
        return String(format: "%.2f M", size / (1024 * 1024))
    }
    
    // 清除缓存
    static public func clearCache() {
        // 取出cache文件夹目录，缓存文件都在这个目录下
        guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else { return }
        
        // 取出文件夹下所有文件数组
//        let fileArr = try? FileManager.default.contentsOfDirectory(atPath: cachePath)
        let fileArr = FileManager.default.subpaths(atPath: cachePath)
        
        var size: Float = 0
        fileArr?.forEach { file in
            // 把文件名拼接到路径中
            let path = cachePath.appending("/\(file)")
            
            // 删除文件
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                } catch {
                    
                }
            }
        }
    }
    
}
